package com.service.impl;

import com.dto.UnloadGoodsDTO;
import com.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.*;
import com.service.GoodsService;
import com.service.UnloadGoodsService;
import com.util.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UnloadGoodsServiceImpl implements UnloadGoodsService {
    @Autowired
    UnloadGoodsMapper unloadGoodsMapper;
    @Autowired
    CurrentUser currentUser;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    GoodsEntityMapper goodsEntityMapper;
    @Autowired
    PurOrderMapper purOrderMapper;
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    PurNoteMapper purNoteMapper;
    @Autowired
    ProducedMapper producedMapper;

    @Override
    public PageBean<UnloadGoodsDTO> getAll(Integer pageIndex, Integer pageSize, UnloadGoodsDTO unloadGoodsDTO) {
        PageHelper.startPage(pageIndex, pageSize);
        unloadGoodsDTO.setIOEmployee(currentUser.getCurrentEname());
        unloadGoodsDTO.setApproveMan(currentUser.getCurrentEname());
        List<UnloadGoodsDTO> list= unloadGoodsMapper.selectAll(unloadGoodsDTO);
        List<UnloadGoodsDTO> newList=new ArrayList<>();
        Employee employee = employeeMapper.findByEid(currentUser.getCurrentEid());
        //实现当前用户展示当前用户的
        //1是管理员，2是普通用户
        if(employee.getRid().equals(1)){
            for (UnloadGoodsDTO goodsDTO : list) {
                //管理员就过滤自己审核的和自己申请的
//                 if("真库管".equals(goodsDTO.getApproveMan()) || "真库管".equals(goodsDTO.getIOEmployee())){
                if(currentUser.getCurrentEname().equals(goodsDTO.getApproveMan()) || currentUser.getCurrentEname().equals(goodsDTO.getIOEmployee())){
                    newList.add(goodsDTO);
                }
            }
        }else{
            //非管理员就自己显示自己对接的||申请的
            for (UnloadGoodsDTO goodsDTO : list) {
                if(currentUser.getCurrentEname().equals(goodsDTO.getIOEmployee())){
                    newList.add(goodsDTO);
                }
            }
        }
        PageInfo<UnloadGoodsDTO> pageInfo = new PageInfo<>(newList);
        PageBean<UnloadGoodsDTO> pageBean = new PageBean<>(
                pageIndex,
                pageSize,
                pageInfo.getPages(),
                (int)pageInfo.getTotal(),
                pageInfo.getList()
        );
        return pageBean;
    }
    @Override
    public void addUnloadGoods(UnloadGoods unloadGoods) {
            //添加入库
        unloadGoodsMapper.insert(unloadGoods);

    }
    @Override
    @Transactional
    public void modify(UnloadGoodsDTO unloadGoodsDTO) {
            log.info("当前审批人：{}",unloadGoodsDTO.getApproveMan());
            log.info("当前登录人：{}",currentUser.getCurrentEname());
        if(!(currentUser.getCurrentEname().equals(unloadGoodsDTO.getApproveMan()))){
             throw new RuntimeException("非审批人");
            }
//        审核不通过
        if(unloadGoodsDTO.getIsApprove().equals("不通过")){
            ///修改入库记录
            unloadGoodsMapper.modify(unloadGoodsDTO);

            //  不通过则返回生产部
            if (unloadGoodsDTO.getSource().equals("生产入库")){
                String snum = String.valueOf(Double.valueOf(unloadGoodsDTO.getCurrentNumber())/1000);
                String stype="";
                if (unloadGoodsDTO.getGname()!="无水甲酸" && unloadGoodsDTO.getGname()!="丙酮氰醇" && unloadGoodsDTO.getGname()!="乙酰腈" && unloadGoodsDTO.getGname()!="烯丙基三甲硅烷"){
                    stype="原料";
                }else{
                    stype="成品";
                }
                String pressure = "";
                if (unloadGoodsDTO.getCurrentNumber() > 10000){
                    pressure = "需要入库";
                }else{
                    pressure = "库存正常";
                }
                ProductionStore productionStore = new ProductionStore(unloadGoodsDTO.getGname(),snum,"吨",snum+"吨",stype,pressure,null,null);
                producedMapper.modifyProducedStore(productionStore);
            }

            return;
        }


        //审核通过
        //修改总数
        //查找总数
        System.out.println(unloadGoodsDTO.getGoodsUniqueNo());
        GoodsEntity goodsEntity = goodsEntityMapper.findByGoodsUniqueNo(unloadGoodsDTO.getGoodsUniqueNo());
        goodsEntity.setSum(goodsEntity.getSum()+unloadGoodsDTO.getCurrentNumber());
        goodsEntityMapper.modify(goodsEntity);
        //比较时间差，当前审核时间要比预计入库时间早
        String storageTime = unloadGoodsDTO.getStorageTime();
        Calendar calendar = Calendar.getInstance();
        Calendar calendar1 = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat("yyyy/MM/dd").parse(storageTime));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            //今日零时毫秒值
            calendar1.setTime(new SimpleDateFormat("yyyy/MM/dd").parse( sdf.format(new Date())));
            long currentTime = calendar1.getTimeInMillis();
            long timeInMillis = calendar.getTimeInMillis();
            if((timeInMillis-currentTime) < 0){
                throw new RuntimeException("入库时间已过，请重新填写入库单");
            }
        } catch (Exception e) {
            unloadGoodsDTO.setIsApprove("不通过");
            unloadGoodsDTO.setIsunload("未入库");
            unloadGoodsMapper.modify(unloadGoodsDTO);
            throw new RuntimeException(e.getMessage());
        }

        ///修改入库记录
        unloadGoodsMapper.modify(unloadGoodsDTO);
        //真二八经入库
        if(unloadGoodsDTO.getOid() == null){
            //生产入库
            Goods goods = this.margeUnloadGoodsAnd(unloadGoodsDTO, goodsEntity);
            goodsMapper.insert(goods);
        }else{
            //查询到采购单对象,采购入库
            PurOrder purOrder = purOrderMapper.findByOid(unloadGoodsDTO.getOid());
            log.info("采购入库审核{}",purOrder);
            //拼接
            Goods goods = this.margeUnloadGoodsAnd(unloadGoodsDTO, purOrder, goodsEntity);
            //修改订单状态
            purNoteMapper.updateStoragedByOid(unloadGoodsDTO.getOid());
            // 添加商品
            goodsMapper.insert(goods);
        }


    }

    /**
     * 无订单审核合并
     * @param unloadGoodsDTO
     * @param goodsEntity
     * @return
     */
    private Goods margeUnloadGoodsAnd(UnloadGoodsDTO unloadGoodsDTO, GoodsEntity goodsEntity) {
        Goods goods  = new Goods();
        goods.setGname(unloadGoodsDTO.getGname());
        goods.setProductType(unloadGoodsDTO.getSource());
        goods.setProduct("成都市");
        goods.setSpecs("90%");
        //后期改
        goods.setBatchNumber("2189219819");
        goods.setApprovalNumber("21892382092");
        goods.setProductUnit("kg");
        //
        goods.setPurchasePrice("/");

        goods.setProcurementTime("/");
        //生产日期
        int mouth = (int)(Math.random()*12)+1;
        int day = (int)(Math.random()*28)+1;
        Boolean flag = "生产入库".equals(unloadGoodsDTO.getSource());
        if(flag){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String format = sdf.format(new Date());
            goods.setProductProductionDate(format);
        } else  {
            goods.setProductProductionDate("23/"+mouth+"/"+day);
        }
        goods.setProductType(goodsEntity.getGoodsSort());
        goods.setSid(-1);
        goods.setNumber(unloadGoodsDTO.getCurrentNumber());
        goods.setGoodsUniqueNo(unloadGoodsDTO.getGoodsUniqueNo());
        goods.setGno(32);
        goods.setAnnex(unloadGoodsDTO.getAnnex());
        goods.setGPhoto("暂无");
        goods.setGoodsDesc("暂无");
        return goods;

    }



//    /入库记录，默认32是存放位置为挑拣区

    /**
     * 销售入库
     * @param unloadGoods
     */
    @Autowired
    private GoodsService goodsService;
    @Override
    public void addUnloadGoodsIsSale(UnloadGoods unloadGoods) {
        log.info("销售退货新增入库");
        unloadGoods.setEid(currentUser.getCurrentEid());//对接人
        List<GoodsEntity> goodsEntities = goodsService.findAll();
        for (GoodsEntity goodsEntity : goodsEntities) {
            //找到输入商品实体
            if (goodsEntity.getGname().equals(unloadGoods.getGname())) {
                unloadGoods.setGoodsUniqueNo(goodsEntity.getGoodsUniqueNo());
                unloadGoods.setBeforeNumber(goodsEntity.getSum());
                unloadGoods.setGid(goodsEntity.getGid());
            }
        }
        unloadGoods.setGno(32);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String format = sdf.format(new Date());
        unloadGoods.setCreationDate(format);
        unloadGoods.setIsApprove("待审核");
        unloadGoods.setIsunload("未入库");
        unloadGoods.setCreationDate(format);
        System.out.println(unloadGoods);
        unloadGoodsMapper.insert(unloadGoods);
    }

    /**
     * 产品入库
     * @param unloadGoods
     */
    @Override
    public void addUnloadGoodsIsProduct(UnloadGoods unloadGoods) {
        log.info("生产入库操作");
        unloadGoods.setGno(33);
        unloadGoods.setIsApprove("待审核");
        unloadGoods.setIsunload("未入库");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String format = sdf.format(new Date());
        unloadGoods.setCreationDate(format);
        unloadGoodsMapper.insert(unloadGoods);
    }


    private Goods margeUnloadGoodsAnd(UnloadGoodsDTO unloadGoods,PurOrder purOrder,GoodsEntity goodsEntity){
        //合并
        Goods goods = new Goods();
        goods.setProductType(unloadGoods.getSource());
        goods.setGname(unloadGoods.getGname());
        goods.setProduct(purOrder.getSupplier().getAddress());
        goods.setSpecs("90%");
        //后期改
        goods.setBatchNumber("2189219819");
        goods.setApprovalNumber("21892382092");
        //价格
        goods.setPurchasePrice((purOrder.getPerprice()).toString());
        goods.setProductUnit(purOrder.getProductUnit());
        goods.setProcurementTime(purOrder.getCreatedate());
        //生产日期
        int mouth = (int)(Math.random()*12)+1;
        int day = (int)(Math.random()*28)+1;
        goods.setProductProductionDate("23/"+mouth+"/"+day);
        goods.setProductType(goodsEntity.getGoodsSort());
        goods.setSid(purOrder.getOid());
        goods.setNumber(unloadGoods.getCurrentNumber());
        goods.setGoodsUniqueNo(unloadGoods.getGoodsUniqueNo());
        goods.setGno(32);
        goods.setAnnex(unloadGoods.getAnnex());
        goods.setGPhoto("暂无");
        goods.setGoodsDesc("暂无");
        return goods;
    }
}
